package my.android.call;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import java.util.List;

/**
 * Created by dinhthao on 6/25/13.
 */
public class ReceiverInCommingCall extends BroadcastReceiver {
    public static Context con;
    private static long timeStart = -1L;
    private static long timeEnd;

    @Override
    public void onReceive(Context context, Intent intent) {
        con = context;
        try{
            TelephonyManager phone = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            MyPhoneStateListener PhoneListener = new MyPhoneStateListener();
            phone.listen(PhoneListener, PhoneStateListener.LISTEN_CALL_STATE);

        }catch (Exception e){

        }

    }

    private class MyPhoneStateListener extends PhoneStateListener{
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            if(state == TelephonyManager.CALL_STATE_RINGING){
                Toast.makeText(con, "Incomming call from: " + incomingNumber, Toast.LENGTH_LONG).show();
            }

            //when my phone answer...
            if(state == TelephonyManager.CALL_STATE_OFFHOOK){
                timeStart = System.currentTimeMillis();
                Toast.makeText(con, "start incoming call... " + incomingNumber, Toast.LENGTH_LONG).show();
            }

            //end call
            if(state == TelephonyManager.CALL_STATE_IDLE && timeStart != -1L){
                Toast.makeText(con, "end incoming call... " + incomingNumber, Toast.LENGTH_LONG).show();

            }

            //ghi am cac cuoc goi lai, sau khi ket thuc se kiem tra call log xem do la loai cuoc goi nao
            //neu la incomming hoac outgoing thi gui vao mail roi xoa di, neu la miss call thi xoa luon

        }

        @Override
        public void onDataConnectionStateChanged(int state) {
            super.onDataConnectionStateChanged(state);
            Toast.makeText(con, "onDataConnectionStateChanged", Toast.LENGTH_LONG).show();
        }


    }




}
